const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const app = express();
const path = require('path');
const port = process.env.PORT || 3000;
const os = require('os');
const { exec } = require('child_process'); 
// 引入数据库连接池
const pool = require('./db'); // 确保路径正确

// 引入路由模块
const userRoutes = require('./routes/userRoutes');
const courseRoutes = require('./routes/courseRoutes');
const chapterRoutes = require('./routes/chapterRoutes');
const resourceRoutes = require('./routes/resourceRoutes');
const classRoutes = require('./routes/classRoutes');
const codelineRoutes = require('./routes/codelineRoutes'); 
const practiceRoutes = require('./routes/practiceRoutes');
const questionRoutes = require('./routes/questionRoutes'); 
const answerRoutes = require('./routes/answerRoutes'); 
const collectQuestionRoutes = require('./routes/collectQuestionRoutes'); 
const questionReviewRoutes = require('./routes/questionReviewRoutes');
const tutorManageRoutes = require('./routes/tutorManageRoutes');

app.use(bodyParser.json());
app.use(express.static('public'));

// 配置会话中间件
app.use(session({
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: false
}));

// 验证用户是否登录的中间件
const requireLogin = (req, res, next) => {
    if (!req.session.username) {
        return res.redirect('/login.html');
    }
    next();
};

app.get('/', (req, res) =>{
    res.redirect('/register.html');
});
// 使用路由
app.use(express.static(path.join(__dirname, 'public'))); 
app.use('/css', express.static(path.join(__dirname, 'public/css')));
app.use('/js', express.static(path.join(__dirname, 'public/js')));
app.use('/', userRoutes);
app.use('/', courseRoutes);
app.use('/', chapterRoutes);
app.use('/', resourceRoutes);
app.use('/', classRoutes);
app.use('/',codelineRoutes);
app.use('/', practiceRoutes); 
app.use('/', questionRoutes); 
app.use('/', answerRoutes); 
app.use('/', collectQuestionRoutes); 
app.use('/', questionReviewRoutes);
app.use('/', tutorManageRoutes); 

// 对需要登录才能访问的页面使用中间件
app.get('/success.html', requireLogin, (req, res) => {
    res.sendFile(__dirname + '/public/success.html');
});

app.get('/edit-profile.html', requireLogin, (req, res) => {
    res.sendFile(__dirname + '/public/edit-profile.html');
});

// === 自动建表函数 ===
const createTables = async () => {
    const tables = [
        `CREATE TABLE IF NOT EXISTS chapters (
            chapter_id varchar(255) NOT NULL,
            chapter_title varchar(255) NOT NULL,
            chapter_content text NOT NULL,
            course_code varchar(255) NOT NULL,
            chapter_order int NOT NULL,
            PRIMARY KEY (chapter_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS choice_questions (
            id int NOT NULL AUTO_INCREMENT,
            practice_id varchar(255) NOT NULL,
            question text NOT NULL,
            option_a text NOT NULL,
            option_b text NOT NULL,
            option_c text,
            option_d text,
            correct_answer char(1) NOT NULL,
            score int NOT NULL,
            question_order int NOT NULL DEFAULT '1',
            PRIMARY KEY (id)
        ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS class_attention (
            user_id varchar(255) NOT NULL,
            class_code varchar(255) NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS classes (
            class_code varchar(255) NOT NULL,
            class_name varchar(255) NOT NULL,
            class_creator_id varchar(255) DEFAULT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS commited_choice_question (
            practice_id varchar(50) NOT NULL,
            question_order int NOT NULL,
            commited_answer char(1) NOT NULL,
            score int DEFAULT NULL,
            commit_user_id varchar(50) DEFAULT NULL,
            is_collected int DEFAULT '0'
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS commited_essay_question (
            practice_id varchar(50) NOT NULL,
            question_order int NOT NULL,
            commited_answer text,
            score int DEFAULT NULL,
            commit_user_id varchar(50) DEFAULT NULL,
            is_collected int DEFAULT '0'
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS commited_fill_question (
            practice_id varchar(50) NOT NULL,
            question_order int NOT NULL,
            commited_answer1 varchar(255) DEFAULT NULL,
            commited_answer2 varchar(255) DEFAULT NULL,
            commited_answer3 varchar(255) DEFAULT NULL,
            score int DEFAULT NULL,
            commit_user_id varchar(50) DEFAULT NULL,
            is_collected int DEFAULT '0'
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS commited_practice (
            practice_id varchar(50) NOT NULL,
            commit_user_id varchar(50) NOT NULL,
            remaining_submit_times int NOT NULL,
            submit_time datetime DEFAULT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS course_selection (
            student_id varchar(255) NOT NULL,
            course_code varchar(20) NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS courses (
            id int NOT NULL AUTO_INCREMENT,
            course_name varchar(255) NOT NULL,
            course_code varchar(255) NOT NULL,
            syllabus text NOT NULL,
            teaching_objectives text NOT NULL,
            assessment_method text NOT NULL,
            teacher_user_id varchar(255) DEFAULT NULL,
            credits double DEFAULT NULL,
            study_period int DEFAULT NULL,
            place varchar(255) DEFAULT NULL,
            course_time varchar(255) DEFAULT NULL,
            teach_weeks varchar(255) DEFAULT NULL,
            PRIMARY KEY (id)
        ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS essay_questions (
            id int NOT NULL AUTO_INCREMENT,
            practice_id varchar(255) NOT NULL,
            question text NOT NULL,
            score int NOT NULL,
            question_order int NOT NULL DEFAULT '1',
            PRIMARY KEY (id)
        ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS fill_questions (
            id int NOT NULL AUTO_INCREMENT,
            practice_id varchar(255) NOT NULL,
            question text NOT NULL,
            blank1_answer varchar(255) DEFAULT NULL,
            blank1_score int DEFAULT NULL,
            blank2_answer varchar(255) DEFAULT NULL,
            blank2_score int DEFAULT NULL,
            blank3_answer varchar(255) DEFAULT NULL,
            blank3_score int DEFAULT NULL,
            question_order int NOT NULL DEFAULT '1',
            PRIMARY KEY (id)
        ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS incorrect_question (
            practice_id varchar(50) NOT NULL,
            user_id varchar(50) NOT NULL,
            question_order int NOT NULL,
            max_correct_times int NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS learned_resource (
            resource_id varchar(255) NOT NULL,
            user_id varchar(255) NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS practice (
            practice_id varchar(255) DEFAULT NULL,
            course_code varchar(255) DEFAULT NULL,
            start_time date DEFAULT NULL,
            deadline date DEFAULT NULL,
            submit_times varchar(255) DEFAULT NULL,
            practice_name varchar(255) NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS resources (
            resource_id varchar(255) NOT NULL,
            resource_content text,
            course_code varchar(255) DEFAULT NULL,
            uploader_user_id varchar(255) DEFAULT NULL,
            create_time timestamp NULL DEFAULT CURRENT_TIMESTAMP,
            permission varchar(255) DEFAULT NULL,
            attachment varchar(255) DEFAULT '0',
            belong_chapter varchar(255) DEFAULT NULL,
            PRIMARY KEY (resource_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

        `CREATE TABLE IF NOT EXISTS tutors (
            tutor_id varchar(255) NOT NULL,
            course_code varchar(255) NOT NULL,
            tutor_name varchar(255) NOT NULL,
            tutor_student_id varchar(255) NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`,

`CREATE TABLE if not exists users (
  user_id varchar(255) NOT NULL,
  username varchar(255) NOT NULL,
  email varchar(255) NOT NULL,
  password varchar(255) NOT NULL,
  name varchar(255) DEFAULT '',
  student_id varchar(255) DEFAULT '',
  student_id_hash varchar(64) DEFAULT NULL,
  role enum('教师','助教','学生') DEFAULT '学生',
  is_logged_in tinyint(1) DEFAULT '0',
  session_id varchar(255) DEFAULT NULL,
  device_id varchar(255) DEFAULT NULL,
  username_hash varchar(255) DEFAULT NULL,
  PRIMARY KEY (user_id),
  UNIQUE KEY username (username),
  UNIQUE KEY username_hash (username_hash)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci`   ];

    try {
        for (const table of tables) {
            await pool.query(table);
        }
        console.log('✅ 数据库表已成功创建/验证');
    } catch (err) {
        console.error('❌ 建表过程中出错:', err);
    }
};

// 获取服务器的无线局域网(WLAN)IPv4地址
function getNetworkIP() {
    const interfaces = os.networkInterfaces();
    const results = [];
    
    for (const name of Object.keys(interfaces)) {
        // 排除虚拟接口和回环地址
        if (name.startsWith('lo') || 
            name.startsWith('veth') || 
            name.includes('docker') || 
            name.includes('virtual')) continue;
            
        for (const iface of interfaces[name]) {
            // 跳过 IPv6 和内部地址
            if (iface.family !== 'IPv4' || iface.internal) continue;
            
            // 优先选择无线接口
            if (name.toLowerCase().includes('wl') || 
                name.toLowerCase().includes('wi') || 
                name.toLowerCase().includes('wireless')) {
                return iface.address; // 立即返回无线接口地址
            }
            results.push(iface.address);
        }
    }
    return results[0] || '127.0.0.1'; // 返回第一个找到的地址
}
// 自动打开浏览器的函数
function openBrowser(url) {
    const platform = process.platform;
    let command;
    switch(platform) {
        case 'darwin': // macOS
            command = `open "${url}"`;
            break;
        case 'win32': // Windows
            command = `start "" "${url}"`;
            break;
        default: // Linux及其他
            command = `xdg-open "${url}"`;
    }
    
    exec(command, (error) =>{
        if(error) {
            console.error(`无法自动打开浏览器: ${error}`);
        }
    });
}

// 启动服务器前先创建表
(async () => {
    await createTables();
    
    // 启动服务器并保存实例
    const server = app.listen(port, '0.0.0.0', () => {
        const allIPs = getAllNetworkIPs();
        const mainIP = getNetworkIP();
        
        console.log(`🚀🚀 服务器运行中`);
        console.log(`📡📡 可用访问地址:`);
        
        allIPs.forEach(ip => {
            console.log(`  → http://${ip}:${port}/register.html`);
        });
        
        console.log(`💡💡 请使用上述任一地址访问（推荐第一个）`);
        openBrowser(`http://${mainIP}:${port}/register.html`);
    });

    // 优雅关闭处理
    const gracefulShutdown = (signal) => {
        console.log(`🛑 收到 ${signal} 信号，开始关闭服务器...`);
        
        // 1. 停止接收新请求
        server.close(async () => {
            console.log('🔴 HTTP 服务器已关闭');
            
            // 2. 关闭数据库连接池
            try {
                await pool.end();
                console.log('✅ 数据库连接池已关闭');
            } catch (err) {
                console.error('❌ 关闭数据库连接池时出错:', err);
            }
            
            // 3. 退出进程
            console.log('👋 进程退出');
            process.exit(0);
        });

        // 如果关闭超时，强制退出
        setTimeout(() => {
            console.error('⏰ 关闭超时，强制退出');
            process.exit(1);
        }, 5000); // 5秒超时
    };

    // 监听各种关闭信号
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
    process.on('SIGINT', () => gracefulShutdown('SIGINT'));
    process.on('SIGHUP', () => gracefulShutdown('SIGHUP'));
    
    // 监听未处理的Promise拒绝
    process.on('unhandledRejection', (reason, promise) => {
        console.error('⚠️ 未处理的Promise拒绝:', reason);
        // 可以考虑优雅关闭
        gracefulShutdown('UNHANDLED_REJECTION');
    });
})();
// 获取所有有效 IP 地址
function getAllNetworkIPs() {
    const interfaces = os.networkInterfaces();
    const ips = [];
    
    for (const name of Object.keys(interfaces)) {
        for (const iface of interfaces[name]) {
            if (iface.family === 'IPv4' && !iface.internal) {
                // 添加接口类型标识
                const type = name.toLowerCase().includes('wl') ? '[无线] ' : 
                            name.toLowerCase().includes('eth') ? '[有线] ' : '';
                ips.push(`${iface.address}`);
            }
        }
    }
    return ips.length ? ips : ['127.0.0.1'];
}